package com.zqq.netty;

import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ChannelHandle extends SimpleChannelInboundHandler<ByteBuf> {

    private static final String TAG = "bl_netty";

    private NettyManager nettyManager;

    public ChannelHandle(NettyManager nettyManager) {
        this.nettyManager = nettyManager;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        //成功
        Log.i(TAG,"channelActive");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        //连接失败
        Log.i(TAG,"channelInactive 连接失败");
        if (nettyManager != null) {
            nettyManager.reConnect(); //重新连接
        }
    }

    /**
     * 心跳检测  当设置时间没有收到事件 会调用
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state().equals(IdleState.WRITER_IDLE)) { //写超时，此时可以发送心跳数据给服务器
                Log.i(TAG, "userEventTriggered write idle");
                if (nettyManager == null){
                    return;
                }
            }else if (idleStateEvent.state().equals(IdleState.READER_IDLE)){   //读超时，此时代表没有收到心跳返回可以关闭当前连接进行重连
                Log.i(TAG, "userEventTriggered read idle");
                ctx.channel().close();
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Log.i(TAG, "exceptionCaught");
        cause.printStackTrace();
        ctx.close();

        if (nettyManager != null) {
            nettyManager.reConnect(); //重新连接
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        Log.i(TAG, "channelRead0");
        if (nettyManager == null){
            return;
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);

        Log.i(TAG, "channelRead >>"+msg.getClass());
        if (nettyManager == null){
            return;
        }
        if(msg instanceof byte[]){
            nettyManager.receiveData((byte[]) msg); //重新连接
        }

    }
}